/*
*@功能：ESP32平衡车旋转编码器测速测试
*@作者：刘泽文
*@时间：2020/3/18
*/

#include <WiFi.h>
#include <math.h>

#define interruptPin_A 5     //A相
#define interruptPin_B 18    //B相

#define LED1 19
#define LED2 22
#define LED1_OFF   digitalWrite(LED1, HIGH)//关灯1
#define LED1_ON    digitalWrite(LED1, LOW)//开灯1
#define LED1_PWM   digitalWrite(LED1, !digitalRead(LED1))//灯1闪烁
#define LED2_OFF   digitalWrite(LED2, HIGH)//关灯2
#define LED2_ON    digitalWrite(LED2, LOW)//开灯2
#define LED2_PWM   digitalWrite(LED2, !digitalRead(LED2))//灯2闪烁

long int count = 0;//计数

void handleInterrupt_A() {
  if (digitalRead(interruptPin_A) == LOW){   
    if (digitalRead(interruptPin_B) == LOW){
      count--;//反转
      Serial.print("count: ");
      Serial.println(count);
    }
    else if (digitalRead(interruptPin_B) == HIGH){
      count++;//正转
      Serial.print("count: ");
      Serial.println(count);
    }
  }
  else if(digitalRead(interruptPin_A) == HIGH){
    if (digitalRead(interruptPin_B) == LOW){
      count++;//正转
      Serial.print("count: ");
      Serial.println(count);
    }
    else if (digitalRead(interruptPin_B) == HIGH){
      count--;//反转
      Serial.print("count: ");
      Serial.println(count);
    }
  }
}

void setup(){
  Serial.begin(9600);

  pinMode(interruptPin_A, INPUT_PULLUP);
  pinMode(interruptPin_B, INPUT_PULLUP);
  pinMode(LED1,OUTPUT);
  pinMode(LED2,OUTPUT);
  LED1_OFF;
  LED2_ON;
  
  attachInterrupt(digitalPinToInterrupt(interruptPin_A), handleInterrupt_A, CHANGE);
}

void loop() {
  delay(1000);
  LED1_PWM;
  LED2_PWM;
}